package com.feng.spring.hibernate.extend.core;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.hibernate.transform.AliasToEntityMapResultTransformer;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * sql执行器
 */
public class DefaultHibernateExtendSQLExecutor implements HibernateExtendSQLExecutor {


    @Override
    public void decorate(Map<String, Object> paramsKeyValue) {

    }

    // 执行方法是需要根据项目情况自定义的
    @Override
    public Object execute(Method method, SessionFactory sessionFactory, String sql, List<Object> queryParams) {
        Session session = this.getSession(sessionFactory);

        Query query = session.createNativeQuery(sql);

        for (int i = 0; i < queryParams.size(); i++) {
            query.setParameter(i + 1, queryParams.get(i));
        }

        Class<?> returnType = method.getReturnType();
        String typeName = returnType.getName();
        switch (typeName) {
            case "java.util.List":
                query.setTupleTransformer(AliasToEntityMapResultTransformer.INSTANCE);
                return query.list();
            case "void":  // 一般情况不建议void
                query.executeUpdate();
                return null;
        }
        // session 是否需要关闭，需要根据据项目情况而定，
        // 一般来说获取的不是currentSession则需要手动关闭
        // session.close();
        return null;
    }

    public Session getSession(SessionFactory sessionFactory) {
        Session session;
        try {
            session = getCurrentSession(sessionFactory);
        } catch (HibernateException e) {
            session = openSession(sessionFactory);
        }
        System.out.println("session: " + session);
        return session;
    }

    private Session getCurrentSession(SessionFactory sessionFactory) {
        return sessionFactory.getCurrentSession();
    }

    private Session openSession(SessionFactory sessionFactory) {
        return sessionFactory.openSession();
    }
}
